package com.example.wifi4client;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ReadTask implements Runnable {

    public boolean bStop = false;

    private Socket mSocket;
    private InputStream inputStream;

    private Handler mHandler;

    public ReadTask(Socket socket, Handler handler) {
        mSocket = socket;
        mHandler = handler;

        try {
            inputStream = (mSocket != null) ? mSocket.getInputStream() : null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        while (true) {
            if (bStop)
                break;
            if(mSocket == null)
                break;
            if (mSocket.isConnected() == false)
                break;
            if (mSocket.isClosed() == true)
                break;
            if (inputStream == null)
                break;

            try {
                bytes = inputStream.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

            if (bytes > 0) {
                mHandler.sendEmptyMessage(MainActivity.DEVICE_CONNECTED);
                final byte[] data = new byte[bytes];
                System.arraycopy(buffer, 0, data, 0, bytes);

                Message message = Message.obtain();
                message.what = MainActivity.GET_MSG;
                Bundle bundle = new Bundle();
                bundle.putString("MSG", new String(data));
                message.setData(bundle);
                mHandler.sendMessage(message);
            }

        }
    }
}
